import {iMicroPageServiceProvideData} from "@peryl/micro-web";
import {iMicroAppPageRenderRefer} from "./MicroApp.pageRender";
import {Button, Icon, PageCard} from "plain-design";
import {getFunctionValue} from "@peryl/utils/getFunctionValue";
import {insertSort} from '@peryl/utils/insertSort';
import {Fragment} from "@peryl/react-compose";

/**
 * 页面导航控制模块
 * @author  韦胜健
 * @date    2024.6.12 22:38
 */
export const MicroAppPageNavigation = (() => {

  const useProvider = (pageServiceProvideData: iMicroPageServiceProvideData, pageRenderRefer: iMicroAppPageRenderRefer) => {

    const back = () => pageServiceProvideData.pageConfig.showBackButton && pageServiceProvideData.nav.back();

    pageRenderRefer.hooks.onPageRender.use({
      processor: ({ list, render }) => {
        if (
          !pageServiceProvideData.pageConfig.hideNavigation && (
            pageServiceProvideData.pageConfig.title ||
            pageServiceProvideData.pageConfig.showBackButton ||
            pageServiceProvideData.pageConfig.buttons.length
          )
        ) {
          list.push({ render, seq: 0, key: 'page_navigation' });
        }
      },
      render: () => {
        const { title, showBackButton, buttons, } = pageServiceProvideData.pageConfig;
        return (
          <PageCard className="page-navigation">
            <div className="page-navigation-left">
              {showBackButton && (
                <div className="page-navigation-back" onClick={back}><Icon icon="pi-left"/></div>
              )}
              {!!title && (<div className="page-navigation-title" onClick={back}>{getFunctionValue(title)}</div>)}
            </div>
            <div className="page-navigation-right">
              {insertSort(buttons, (val1, val2) => (val1.seq || 1) > (val2.seq || 1)).map((btn, index) => (
                btn.render ? <Fragment key={btn.code ?? index}>{btn.render()}</Fragment> :
                  <Button
                    key={index}
                    label={getFunctionValue(btn.label, '')}
                    disabled={getFunctionValue(btn.disable, false)}
                    mode={btn.primary ? 'fill' : undefined}
                    onClick={btn.handler}
                    {...btn.buttonAttrs}
                  />
              ))}
            </div>
          </PageCard>
        );
      },
    });
  };

  return { useProvider };
})();
